package com.oa.web.action.organization;

import java.util.List;

import com.oa.model.Organization;
import com.oa.service.organization.OrganizationManager;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;

public class OrganizationAction extends ActionSupport {
	
	private OrganizationManager organizationManager;
    private List<Organization> organizations;
    private Organization organization;
	private Long orgId;
	private Long parentOrgId = 0l;
	
	public String execute() {
        this.organizations = organizationManager.findOrganizationsByParentOrgId(parentOrgId);
        for (Organization organization : organizations) {
        	if (organization.getParentO()!=null) {
        		Organization pOrg = organizationManager.get(organization.getParentO().getId());
        		organization.setParentO(pOrg);
        	}
        }
        return Action.SUCCESS;
    }

    public String save() {
    	this.organizationManager.save(organization);
        this.organization = new Organization();
        return execute();
    }
    
    public String modify() {
    	organization = this.organizationManager.get(orgId);
    	if (organization.getParentO()!=null) {
	    	Organization parentOrg = this.organizationManager.get(organization.getParentO().getId());
	    	organization.setParentO(parentOrg);
    	}
    	return execute();
    }

    public String remove() {
    	organization = organizationManager.get(orgId);
    	if (organization.getParentO()!=null) {
    		parentOrgId = organization.getParentO().getId();
    	}
    	organizationManager.remove(orgId);
    	this.organization = new Organization();
        return execute();
    }

	public OrganizationManager getOrganizationManager() {
		return organizationManager;
	}

	public void setOrganizationManager(OrganizationManager organizationManager) {
		this.organizationManager = organizationManager;
	}

	public List<Organization> getOrganizations() {
		return organizations;
	}

	public void setOrganizations(List<Organization> organizations) {
		this.organizations = organizations;
	}

	public Organization getOrganization() {
		return organization;
	}

	public void setOrganization(Organization organization) {
		this.organization = organization;
	}

	public Long getOrgId() {
		return orgId;
	}

	public void setOrgId(Long orgId) {
		this.orgId = orgId;
	}

	public Long getParentOrgId() {
		return parentOrgId;
	}

	public void setParentOrgId(Long parentOrgId) {
		this.parentOrgId = parentOrgId;
	}
	
	public List<Organization> getAllOrganizations() {
		List<Organization> orgs = organizationManager.getAll();
		return orgs;
	}

}
